
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>spring扩展点BeanPostProcessor | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="说起spring，想必每个开发人员都用过，spring是除了jdk之外java编程中最必不 可少的基础框架，其优秀的编码方式和编程思想，值得每个技术人员学习和参考。">
<meta name="keywords" content="spring扩展点BeanPostProcessor">
<meta property="og:type" content="article">
<meta property="og:title" content="spring扩展点BeanPostProcessor">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2018/09/15/BeanPostProcessor原理及应用场景/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="说起spring，想必每个开发人员都用过，spring是除了jdk之外java编程中最必不 可少的基础框架，其优秀的编码方式和编程思想，值得每个技术人员学习和参考。">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b1.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b2.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b3.png">
<meta property="og:updated_time" content="2018-09-15T15:21:19.535Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring扩展点BeanPostProcessor">
<meta name="twitter:description" content="说起spring，想必每个开发人员都用过，spring是除了jdk之外java编程中最必不 可少的基础框架，其优秀的编码方式和编程思想，值得每个技术人员学习和参考。">
<meta name="twitter:image" content="http://scorpioaeolus.oschina.io/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b1.png">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/" title="spring扩展点BeanPostProcessor" itemprop="url">spring扩展点BeanPostProcessor</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2018-09-15T13:20:37.000Z" itemprop="datePublished"> Published 2018-09-15</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#源码分析"><span class="toc-number">1.</span> <span class="toc-text">源码分析</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#使用场景-amp-编码实现"><span class="toc-number">2.</span> <span class="toc-text">使用场景&编码实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#测试验证"><span class="toc-number">3.</span> <span class="toc-text">测试验证</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
		
		</div>
		
		<pre><code>    说起spring，想必每个开发人员都用过，spring是除了jdk之外java编程中最必不
可少的基础框架，其优秀的编码方式和编程思想，值得每个技术人员学习和参考。
</code></pre><a id="more"></a> 
<pre><code>spring给我们提供了很多扩展接口，方便我们开发过程中spring容器启动时或者启动结
束做一些事情。此篇我们想要讲的是BeanPostProcessor接口的原理和使用方式。
</code></pre><h5 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h5><pre><code>先看一下BeanPostProcessor接口的源码：
</code></pre><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanPostProcessor</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="comment">/**</span></div><div class="line">	 * Apply this BeanPostProcessor to the given new bean instance &lt;i&gt;before&lt;/i&gt; any bean</div><div class="line">	 * initialization callbacks (like InitializingBean's &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</div><div class="line">	 * or a custom init-method). The bean will already be populated with property values.</div><div class="line">	 * The returned bean instance may be a wrapper around the original.</div><div class="line">	 * <span class="doctag">@param</span> bean the new bean instance</div><div class="line">	 * <span class="doctag">@param</span> beanName the name of the bean</div><div class="line">	 * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</div><div class="line">	 * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</div><div class="line">	 * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</div><div class="line">	 * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</div><div class="line">	 */</div><div class="line">	<span class="function">Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</div><div class="line"></div><div class="line">	<span class="comment">/**</span></div><div class="line">	 * Apply this BeanPostProcessor to the given new bean instance &lt;i&gt;after&lt;/i&gt; any bean</div><div class="line">	 * initialization callbacks (like InitializingBean's &#123;<span class="doctag">@code</span> afterPropertiesSet&#125;</div><div class="line">	 * or a custom init-method). The bean will already be populated with property values.</div><div class="line">	 * The returned bean instance may be a wrapper around the original.</div><div class="line">	 * &lt;p&gt;In case of a FactoryBean, this callback will be invoked for both the FactoryBean</div><div class="line">	 * instance and the objects created by the FactoryBean (as of Spring 2.0). The</div><div class="line">	 * post-processor can decide whether to apply to either the FactoryBean or created</div><div class="line">	 * objects or both through corresponding &#123;<span class="doctag">@code</span> bean instanceof FactoryBean&#125; checks.</div><div class="line">	 * &lt;p&gt;This callback will also be invoked after a short-circuiting triggered by a</div><div class="line">	 * &#123;<span class="doctag">@link</span> InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation&#125; method,</div><div class="line">	 * in contrast to all other BeanPostProcessor callbacks.</div><div class="line">	 * <span class="doctag">@param</span> bean the new bean instance</div><div class="line">	 * <span class="doctag">@param</span> beanName the name of the bean</div><div class="line">	 * <span class="doctag">@return</span> the bean instance to use, either the original or a wrapped one;</div><div class="line">	 * if &#123;<span class="doctag">@code</span> null&#125;, no subsequent BeanPostProcessors will be invoked</div><div class="line">	 * <span class="doctag">@throws</span> org.springframework.beans.BeansException in case of errors</div><div class="line">	 * <span class="doctag">@see</span> org.springframework.beans.factory.InitializingBean#afterPropertiesSet</div><div class="line">	 * <span class="doctag">@see</span> org.springframework.beans.factory.FactoryBean</div><div class="line">	 */</div><div class="line">	<span class="function">Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException</span>;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>BeanPostProcessor接口只有两个方法， postProcessBeforeInitialization和postProcessAfterInitialization，
</code></pre><p><strong>1）</strong> postProcessBeforeInitialization方法：将此BeanPostProcessor应用于任何bean初始化回调，作用时机是<br>    InitializingBean的afterPropertiesSet方法或自定义init-method方法之前。bean已经被填充了属性值。返回的bean实例<br>    可以是围绕原件的包装器。<br><strong>2）</strong> postProcessAfterInitialization方法：将此BeanPostProcessor应用于任何bean初始化回调，作用时机是InitializingBean<br>    的afterPropertiesSet方法或自定义init-method方法之后。bean已经被填充了属性值。返回的bean实例可以是围绕原件的<br>    包装器。</p>
<pre><code>也就是说，实现了该接口的实例，可以在bean初始化之前和初始化之前做一些前置或者后置操作。
</code></pre><img src="/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b1.png" alt="BeanPostProcessor" title="BeanPostProcessor">
<h5 id="使用场景-amp-编码实现"><a href="#使用场景-amp-编码实现" class="headerlink" title="使用场景&amp;编码实现"></a>使用场景&amp;编码实现</h5><pre><code>    现在有很多优秀的持久层框架，但是有些公司或者项目架构比较轻量级一些，不想使用持久层框架，会选择自己封装一些
DAO操作或者直接使用spring提供的jdbcTemplate操作数据库，在使用jdbcTemplate操作时为了避免每个DAO都写很多类似或者
重复的sql操作，一般会抽象出一个通用的DAO操作类，例如BaseDao，里边会封装一些泛型的查询和更新操作，然后具体的调用
和实现交给子类实现。
    理论上，BaseDao层已经帮每个子类实现了大部分功能，子类只需要实现个性化逻辑，那么BaseDao就需要持有一个jdbcTemplate
实例，这个jdbcTemplate实例要么是子类以方法调用的形式传进来，要么是BaseDao层持有，在容器启动的时候进行初始化。
根据个人的使用经验来说，肯定是在容器启动的时候初始化，这样可以省去每次调用的时候重复性传参，并且非业务参数，接下来
我们就使用代码实现：
</code></pre><p><strong>BaseDao</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseDao</span> </span>&#123;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String select = <span class="string">"select "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String from = <span class="string">" from "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String where = <span class="string">" where "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String and = <span class="string">" and "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String orderBy = <span class="string">" order by "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String oneEqOne = <span class="string">" 1=1 "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String count = <span class="string">" count "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String sum = <span class="string">" sum "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String allSymbol = <span class="string">"(*) "</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String seqId = <span class="string">"seqId"</span>;</div><div class="line">	<span class="keyword">protected</span> <span class="keyword">static</span> <span class="keyword">final</span> String star = <span class="string">" * "</span>;</div><div class="line"></div><div class="line">	<span class="keyword">protected</span> JdbcOperations jdbcTemplate;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">protected</span> JdbcOperations <span class="title">getJdbcTemplate</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> jdbcTemplate;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setJdbcTemplate</span><span class="params">(JdbcOperations jdbcTemplate)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.jdbcTemplate = jdbcTemplate;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">queryByPrimaryKey</span><span class="params">(String tableName, String primaryKey, Object value, Class&lt;T&gt; clazz)</span> </span>&#123;</div><div class="line">	StringBuilder sqlBuilder = <span class="keyword">new</span> StringBuilder();</div><div class="line">	sqlBuilder.append(select);</div><div class="line">	sqlBuilder.append(star);</div><div class="line">	sqlBuilder.append(from);</div><div class="line">	sqlBuilder.append(tableName);</div><div class="line">	<span class="keyword">if</span> (<span class="keyword">null</span> == primaryKey || <span class="number">0</span> &gt;= primaryKey.length()) &#123;</div><div class="line">		primaryKey = <span class="string">"id"</span>;</div><div class="line">	&#125;</div><div class="line">	sqlBuilder.append(where);</div><div class="line">	sqlBuilder.append(primaryKey);</div><div class="line">	sqlBuilder.append(<span class="string">"  = ? limit 1 "</span>);</div><div class="line">	log.debug(<span class="string">"querySql-&#123;&#125;"</span>,sqlBuilder.toString());</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.querySingleObj(clazz, sqlBuilder.toString(), <span class="keyword">new</span> Object[]&#123;value&#125;);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">    <span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">queryByPrimaryKey</span><span class="params">(String tableName, Object value, Class&lt;T&gt; clazz)</span> </span>&#123;</div><div class="line">	<span class="keyword">return</span> <span class="keyword">this</span>.queryByPrimaryKey(tableName, <span class="keyword">null</span>, value, clazz);</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p><strong>UserDao</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Repository</span>(<span class="string">"user2Dao"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User2Dao</span> <span class="keyword">extends</span> <span class="title">BaseDao</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TABLE_NAME = <span class="string">"User"</span>;</div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">queryByPk</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.queryByPrimaryKey(TABLE_NAME,id,User.class);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>DataSourceConfig</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 数据源配置类</div><div class="line"> *</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataSourceConfig</span> <span class="keyword">implements</span> <span class="title">BeanPostProcessor</span> </span>&#123;</div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> JdbcTemplate jdbcTemplate;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</div><div class="line">        <span class="keyword">if</span>(bean <span class="keyword">instanceof</span> BaseDao) &#123;</div><div class="line">            ((BaseDao)bean).setJdbcTemplate(jdbcTemplate);</div><div class="line">            System.out.println(beanName + <span class="string">"完成设置jdbcTemplate"</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> bean;</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</div><div class="line">        <span class="keyword">return</span> bean;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>SpringBootConfig</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringBootConfig</span> </span>&#123;</div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> DataSourceConfig  <span class="title">dataSourceConfig</span><span class="params">()</span> </span>&#123;</div><div class="line">        DataSourceConfig dataSourceConfig = <span class="keyword">new</span> DataSourceConfig();</div><div class="line">        <span class="keyword">return</span> dataSourceConfig;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>    最重要的就是DataSourceConfig这个类，DataSourceConfig实现了BeanPostProcessor接口，在实现
postProcessBeforeInitialization中，判断bean是不是BaseDao的实例，如果是就把jdbcTemplate注入进去。
作用就是在spring容器实例化了所有实现了BaseDao的子类之后，在调用初始化方法之前把jdbcTemplate填充
进去，这样的话在调用每个子类Dao的时候jdbcTemplate都完成了初始化，就可以进行查询和更新操作了。
</code></pre><h5 id="测试验证"><a href="#测试验证" class="headerlink" title="测试验证"></a>测试验证</h5><pre><code>针对上一步中的编码，我们首先启动springboot服务：
</code></pre><img src="/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b2.png" alt="BeanPostProcessor" title="BeanPostProcessor">
<pre><code>    可以看到，在spring容器启动过程中给所有BaseDao的子类实例都填充了jdbcTemplate属性。既然容器启动
没问题，接着我们编写测试代码测试一下Dao操作有没有问题：
</code></pre><p><strong>UserManager</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Service</span>(<span class="string">"userManager"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserManager</span> </span>&#123;</div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> User2Dao user2Dao;</div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">queryById</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.user2Dao.queryByPk(id);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>UserController</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@RestController</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> UserManager userManager;</div><div class="line"></div><div class="line">    <span class="meta">@RequestMapping</span>(<span class="string">"user/get/&#123;id&#125;"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">queryUser</span><span class="params">(@PathVariable(<span class="string">"id"</span>)</span> Long id) </span>&#123;</div><div class="line">        User user = <span class="keyword">this</span>.userManager.queryById(id);</div><div class="line">        <span class="keyword">return</span> user;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>再次启动应用，并从浏览器发起请求：
</code></pre><img src="/typhoon/2018/09/15/BeanPostProcessor原理及应用场景/b3.png" alt="BeanPostProcessor" title="BeanPostProcessor">
<pre><code>得到正常响应，说明我们之前的jdbcTemplate注入没有问题，可以像之前的实现方式一样访问DB。
</code></pre><h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><pre><code>    BeanPostProcessor是Spring IOC容器给我们提供的一个扩展接口。BeanPostProcessor的实现类
注册到Spring IOC容器后，对于该Spring IOC容器所创建的每个bean实例在初始化方法（如afterPropertiesSet
和任意已声明的init方法）调用前，将会调用BeanPostProcessor中的postProcessBeforeInitialization方法，
而在bean实例初始化方法调用完成后，则会调用BeanPostProcessor中的postProcessAfterInitialization方法。
    spring扩展接口中还有一个BeanFactoryPostProcessor与BeanPostProcessor比较类似，使用方式基本相似
但是作用时机有所不同，实现BeanFactoryPostProcessor接口，可以在spring的bean创建之前，修改bean的定义
属性，BeanFactoryPostProcessor是在spring容器加载了bean的定义文件之后，在bean实例化之前执行的。
</code></pre>  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/spring/">spring</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/spring扩展点BeanPostProcessor/">spring扩展点BeanPostProcessor</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2018/09/15/BeanPostProcessor原理及应用场景/" data-title="spring扩展点BeanPostProcessor | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2018/09/16/spring实现事务管理/" title="spring实现事务管理">
  <strong>上一篇：</strong><br/>
  <span>
  spring实现事务管理</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2018/09/15/线程池ThreadPoolExecuter使用详解/"  title="线程池ThreadPoolExecuter使用详解">
 <strong>下一篇：</strong><br/> 
 <span>线程池ThreadPoolExecuter使用详解
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#源码分析"><span class="toc-number">1.</span> <span class="toc-text">源码分析</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#使用场景-amp-编码实现"><span class="toc-number">2.</span> <span class="toc-text">使用场景&编码实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#测试验证"><span class="toc-number">3.</span> <span class="toc-text">测试验证</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
